package com.gongj.hystrix.Command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import org.springframework.web.client.RestTemplate;

/**
 * @program: cloudlx
 * @description:请求命令就是以继承类的方式来替代前面的注解方式。
 * @author: gongj
 * @Description: TODO
 * @create: 2020-06-19 11:03
 **/
public class MyHystrixCommand extends HystrixCommand {

   private RestTemplate restTemplate;
    private String name;
    public MyHystrixCommand(Setter setter,RestTemplate restTemplate,String name) {
        super(setter);
        this.restTemplate = restTemplate;
        this.name = name;
    }

    @Override
    protected Object run() {
        String forObject = restTemplate.getForObject("http://appUser/api/user/getName?name={1}", String.class, name);
        return forObject;
    }

    @Override
    protected Object getFallback() {
        Throwable executionException = getExecutionException();
        System.out.println(executionException.getMessage() + "===");
        System.out.println(executionException.fillInStackTrace()  + "===");
        executionException.printStackTrace();
        return "error";
    }


    //开启缓存功能
    @Override
    protected String getCacheKey() {
        return name;
    }

    public static void flushCache(String name) {
        //刷新缓存，根据name进行清理
        HystrixRequestCache.getInstance(
                HystrixCommandKey.Factory.asKey("gongjie"),
                HystrixConcurrencyStrategyDefault.getInstance())
                .clear(String.valueOf(name));
    }
}
